import { useEffect } from 'react';
import { Adjust } from 'react-native-adjust';
import BootSplash from 'react-native-bootsplash';
import { requestTrackingPermission } from 'react-native-tracking-transparency';
import { useDispatch, useSelector } from 'react-redux';

import { useNetInfo } from '@react-native-community/netinfo';

import { requestToken } from '@/api';
import { ACCESS_TOKEN } from '@/constants';
import { setInfo, setLogin, setUserId } from '@/stores/slice/userSlice';
import { RootState } from '@/stores/store';
import { getUserMemberInfo } from '@/utils';
import { AdjustEventsUtil } from '@/utils/adjust';
import { getStorageItem } from '@/utils/storage';
import { initXgPush, startXgPush } from '@/utils/XgPush';

const useInitialize = () => {
  const userId = useSelector((state: RootState) => state.user.userId);
  const { isConnected } = useNetInfo();
  const dispatch = useDispatch();

  // 请求用户是否同意应用追踪
  useEffect(() => {
    if (!isConnected) {
      return;
    }
    requestTrackingPermission().catch((e) => console.log(e));
  }, [isConnected]);

  useEffect(() => {
    if (!isConnected) return;
    if (userId) return;
    // 获取用户ID
    requestToken().then(async (res) => {
      if (getStorageItem(ACCESS_TOKEN)) {
        // 获取用户会员信息，并且设置本地存储
        const user = await getUserMemberInfo();
        dispatch(setInfo(user || null));
        dispatch(setLogin(true));
        dispatch(setUserId(res?.userId ?? ''));
      }

      // adjust 初始化
      AdjustEventsUtil.config();

      AdjustEventsUtil.first_load();
    });

    return () => {
      Adjust.componentWillUnmount();
    };
  }, [isConnected, userId]);

  useEffect(() => {
    setTimeout(() => BootSplash.hide({ fade: true }), 500);
  }, []);

  useEffect(() => {
    initXgPush();
  }, []);

  useEffect(() => {
    if (userId) {
      startXgPush();
    }
  }, [userId]);

  return { isConnected };
};

export default useInitialize;
